<template>
	<view class="sp-section sp-oa sp-room">
		<u-navbar title="" :placeholder="true" bgColor="rgba(0, 0, 0, 0)"/>
		<!-- back -->
		<view class="sp-room__back"></view>
		<!-- 栏位图 -->
		<view class="sp-room__map">
			<view class="sp-room__map-title">栋舍结构图</view>
			<view class="sp-room__map-content">
				<label>{{ buildName }}</label>
				<scroll-view scroll-x="true" style="width: 750rpx;">
					<view class="sp-room__scroll-list" v-for="(item, $index) in areaList" :key="$index" :style="{ width: item.length * 130 + 'rpx' }">
						<!-- #ifdef APP -->
						<view
							class="sp-room__scroll-item"
							v-for="(column, $column) in item"
							:key="$column"
							:class="{
								'warning': column.status == 2,
								'danger': column.status == 4,
								'active': column.status == 3,
								'disabled': !column.has_pig
							}"
							@click="setLogsTips(column.id, column.name, column.has_pig, column.status)"
						>
							{{ column.name }}
						</view>
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<view
							class="sp-room__scroll-item"
							v-for="(column, $column) in item"
							:key="$column"
							:class="{
								'warning': column.status == 2,
								'danger': column.status == 4,
								'active': column.status == 3,
								'disabled': !column.has_pig
							}"
							@click="setLogsTipsH5(column.id, column.name, column.has_pig, column.status)"
						>
							{{ column.name }}
						</view>
						<!-- #endif -->
					</view>
				</scroll-view>
			</view>
		</view>
		
		<!-- 拍照记录 -->
		<view class="sp-room__logs">
			<view class="sp-room__logs-title" style="margin-bottom: 0;">拍照记录</view>
			
			<view class="sp-room__logs-list">
				<template v-if="history && history.length">
					<view class="sp-room__logs-item" v-for="(item, $index) in history" :key="$index" @click="$u.route('/pages/index/room', { info: JSON.stringify(item) })">
						<view class="sp-room__logs-pics">
							<image :src="item.image + '?x-oss-process=image/resize,m_fixed,w_174,h_231'"></image>
						</view>
						<view class="sp-room__logs-info">
							<view class="sp-room__logs-name">栏位: {{ item.column_name }}</view>
							<view class="sp-room__logs-desc">{{ item.operation_time }}</view>
							<view class="sp-room__logs-tags">
								<sp-tag :text="item.ai_has_feed" />
								<!-- <u-tag :text="item.ai_has_feed" :bgColor="colorMap[item.ai_has_feed]" size="mini" /> -->
							</view>
						</view>
					</view>
				</template>
				<template v-else>
					<view style="flex: 1;"><sp-empty /></view>
				</template>
			</view>
		</view>
		
		<view style="height: 140rpx;"></view>
		
		<!-- 开始拍照 -->
		<view class="sp-room__submit">
			<button @click="setPicsTipsStatus">开始拍照</button>
			<!-- #ifdef H5 -->
			<!-- <button v-if="offlineLens" @click="saveOfflineAlls">全部上传</button> -->
			<!-- #endif -->
			<!-- #ifndef H5 -->
			<button v-if="offlineLens" @click="saveOfflineAlls">上传离线文件</button>
			<!-- #endif -->
		</view>
		
		<!-- 拍照提示弹窗 -->
		<u-popup :show="picsTipsStatus" :round="16" mode="center" closeable @close="setPicsTipsStatus">
			<view class="sp-room__tips">
				<image src="../../static/images/room/tips.png"></image>
				<text>对着料槽位置，放大拍照，拍全槽位，效果如下图: </text>
				<view class="sp-room__tips-list">
					<view class="sp-room__tips-pics">
						<image src="../../static/images/room/room-f.png"></image>
						<text>方形槽位</text>
					</view>
					<view class="sp-room__tips-pics">
						<image src="../../static/images/room/room-y.png"></image>
						<text>圆形槽位</text>
					</view>
				</view>
				<!-- #ifdef H5 -->
				<view class="sp-room__tips-submit" @click="chooseImageH5">拍照</view>
				<!-- #endif -->
				<!-- #ifdef APP -->
				<view class="sp-room__tips-submit" @click="chooseImage">拍照</view>
				<!-- #endif -->
			</view>
		</u-popup>
		
		<!-- 拍照成功之后的设置弹窗 -->
		<u-popup :show="logsTipsStatus" closeable @close="setLogsTipsStatus">
			<!-- #ifdef APP -->
			<view class="sp-room__form" :key="logsKey" v-if="offlineIndex > -1">
				<!-- 预览 -->
				<view class="sp-room__form-pics">
					<image :src="offlineInfo[offlineIndex].poster" mode="aspectFit" @click="previewImage" />
					<text @click="setLogsTips(offlineInfo[offlineIndex].id, offlineInfo[offlineIndex].name, true, 1)">重拍</text>
					<text @click="delLogsTips(offlineIndex)">删除</text>
				</view>
				<!-- 表单 -->
				<view class="sp-room__form-ccontent" style="flex-shrink: 0;">
					<u-cell label="栏位" :border="false" @click="areaStatus = true;" :key="offlineInfo[offlineIndex].info.column_id" :value="offlineInfo[offlineIndex].info.column_name"></u-cell>
				</view>
				<view class="sp-room__submit" style="display: flex;">
					<text class="sp-room__link" @click="cancel">取消</text>
					<!-- #ifdef APP -->
					<button @click="saveOffline" style="flex: 1;">保存</button>
					<button @click="saveOfflineNext" v-if="offlineIndex !== offlineInfo.length - 1" style="flex: 2; margin-left: 20rpx;">
						保存并下一栏
					</button>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<button @click="save(false)" style="flex: 1;">保存</button>
					<!-- <button @click="save(true)" style="flex: 2; margin-left: 20rpx;" v-if="hasPoster.length !== area.length">
						保存并下一栏
					</button> -->
					<!-- #endif -->
				</view>
			</view>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<view class="sp-room__form">
				<!-- 预览 -->
				<view class="sp-room__form-pics">
					<image :src="file + logsTipsForm.image" mode="aspectFit" @click="previewImage" />
				</view>
				<!-- 表单 -->
				<view class="sp-room__form-ccontent" style="flex-shrink: 0;">
					<u-cell label="栏位" :border="false" @click="areaStatus = true;" :key="logsTipsForm.column_id" :value="logsTipsForm.column_name"></u-cell>
				</view>
				<view class="sp-room__submit" style="display: flex;">
					<text class="sp-room__link" @click="cancel">取消</text>
					<button @click="save(false)" style="flex: 1;">保存</button>
				</view>
			</view>
			<!-- #endif -->
		</u-popup>

		<!-- 选择栏位 -->
		<u-picker :show="areaStatus" :columns="[areaHasPigs]" keyName="name" closeOnClickOverlay @close="() => { areaStatus = false }" @confirm="setAreaInfo" />
		
		<!-- 日历 -->
		<u-calendar :show="dateStatus" mode="single" :min-date="minDate" :max-date="maxDate" :defaultDate="defaultDate" @close="dateStatus = false" @confirm="getDate"></u-calendar>
	</view>
</template>

<script>
	import dayjs from '@/utils/dayjs.min.js'
	import { file, setOssUpload as uploads, getRecordsById, setRecords } from '@/api/task.js'
	import { getRecordFeedListAsAi } from '@/api/alot.js'
	import uploadFile from '@/utils/uploadAliyun.js'
	import spTag from '@/components/sp-ui/sp-tag.vue'

	export default {
		name: 'spIndex',
		components: {
			spTag
		},
		data () {
			return {
				file,
				flag: true,
				picsTipsStatus: false,
				buildName: '',
				// 时间查询
				minDate: '',
				maxDate: '',
				date: '',
				dateStatus: false,
				// key
				logsKey: 0,
				build: [],
				// 栋舍id
				buildId: null,
				// 料槽形状
				buildShape: null,
				// 栏位
				areaList: [],
				// 已拍照数据
				history: [],
				// 图片文件/地址
				tempFile: [],
				tempFilePaths: [],
				colorMap: {
				  '适量': '#79E984',
				  '偏多': '#FF9F58',
				  '偏少': '#91C1FF',
				  '过满': '#F86060',
				  '空槽': '#59D3D3',
				  '未知': '#C3C3C3',
				  'AI其他': '#fbd950'
				},
				// 提示
				logsTipsStatus: false,
				logsTipsForm: {
					image: '',
					shape: '',
					column_id: '',
					column_name: '请选择',
					building_id: '',
					material_status: '适量',
					occlusion_level: '',
					operation_executed: ''
				},
				// 已拍图片的栏位
				hasPoster: [],
				hasPig: [],
				// 栏位选择
				area: [],
				areaHasPigs: [],
				areaStatus: false,
				// 是否有料
				typeStatus: false,
				typeColumns: [
					{ name: '过满' },
					{ name: '适量' },
					{ name: '空的' },
					{ name: '偏多' },
					{ name: '偏少' },
				],
				// 遮挡程度
				maskStatus: false,
				maskColumns: [
					{ name: '50%以上' }
				],
				maskColumnsIndex: -1,
				// 执行操作
				controlStatus: false,
				controlColumns: [
					{ name: '无' },
					{ name: '调小' },
					{ name: '调大' },
				],
				controlColumnsIndex: -1,
				defaultDate: [],
				// 暂存
				// 临时的文件
				offlineKey: 0,
				offlineTemp: '',
				offlineLens: 0,
				offlineInfo: [],
				offlineIndex: -1,
				offlineNoPoster: true,
				offlineCurrent: 1,
				// 需要上传的文件
				count: 0,
				timer: null,
				uploads: [],
			}
		},
		onLoad (options) {
			this.buildName = options.name
			this.date = dayjs().format('YYYY-MM-DD')
			this.maxDate = dayjs().add(1, 'day').format('YYYY-MM-DD')
			this.minDate = dayjs().subtract(1, 'month').format('YYYY-MM-DD')
			this.buildId = options.id
			this.build = uni.getStorageSync('build')
			// 清空当前离线数组
			this.offlineInfo = []
			const offlineInfo = uni.getStorageSync(`build-${this.buildId}`)
			if (Array.isArray(offlineInfo) && offlineInfo.some(item => item.status == 2)) {
				this.offlineLens = offlineInfo.length
			} else {
				uni.removeStorageSync(`build-${this.buildId}`)
			}
			this.count = 0
			this.uploads = []
			// 如果有id 查询该id下的拍照记录
			if (this.buildId) {
				this.getRecordsList();
			}
			this.defaultDate = [this.date]
		},
		onShow () {},
		created () {},
		mounted () {},
		methods: {
			// 获取时间
			getDate(e) {
				this.date = e[0]
				this.dateStatus = false
				this.defaultDate = [e[0]]
				this.getRecordsList()
			},
			// 预览拍到的栏位图
			previewImage() {
				uni.previewImage({
					urls: [this.offlineInfo[this.offlineIndex].poster]
				})
			},
			// 设置猪只遮挡情况
			setMaskColumnsIndex(index) {
				if (index == this.maskColumnsIndex) {
					this.maskColumnsIndex = -1
					this.offlineInfo[this.offlineIndex].info.occlusion_level = ''
				} else {
					this.maskColumnsIndex = index
					this.offlineInfo[this.offlineIndex].info.occlusion_level = this.maskColumns[index].name
				}
			},
			// 设置操作
			setControlColumnsIndex(index) {
				this.controlColumnsIndex = index
				this.offlineInfo[this.offlineIndex].info.operation_executed = this.controlColumns[index].name
			},
			// 取消当前操作 重置当前栏位为默认
			cancel() {
				// this.offlineInfo[this.offlineIndex].poster = ''
				// this.offlineInfo[this.offlineIndex].status = 1
				// this.offlineInfo[this.offlineIndex].info.material_status = ''
				// this.offlineInfo[this.offlineIndex].info.occlusion_level = '',
				// this.offlineInfo[this.offlineIndex].info.operation_executed = ''
				// const offline = this.offlineInfo.filter(item => item.poster)
				// this.offlineLens = offline.length
				this.logsTipsStatus = false
			},
			// 组织平面图数据
			initMapData() {
				if (this.build && this.build.length) {
				    const area = this.build.find(item => item.id == this.buildId);
					// console.log('area', area)
					// return false
				    if (area && area.farm_scene) {
				        this.buildShape = area.shape ? area.shape : '圆形';
				        const historyIds = this.history && this.history.length ? this.history.map(item => item.column_id) : [];
						this.area = area.farm_scene.map(item => {
				            // const names = item.name.split('-');
				            // item.name = names && names.length > 1 ? names[0] : names[1];
				            const current = this.offlineInfo.find(dv => item.id == dv.id);
				            if (current && current.poster) {
				                item.poster = current.poster;
				                item.status = current.status;
				            } else {
				                item.status = 1;
				            }
				            return item;
				        });
				        this.hasPoster = this.area.filter(item => item.poster);
				        this.areaHasPigs = this.area.filter(item => item.has_pig).reverse();
				        // 根据区域名称进行分组
				        const areaGroups = {
							A: []
						};
						console.log('this.area', this.area)
				        this.area.forEach(item => {
				            const groupName = item.name.match(/[A-Z]/);
							console.log(item.name, groupName)
				            if (groupName) {
				                if (!areaGroups[groupName]) {
				                    areaGroups[groupName] = [];
				                }
				                areaGroups[groupName].push(item);
				            } else {
								areaGroups['A'].push(item)
							}
				        });
						console.log('this,.area', areaGroups)
				        // 将分组排序并设置索引
				        const areaList = Object.keys(areaGroups).map(groupName => {
				            const group = areaGroups[groupName].sort((a, b) => {
				                // 提取名称中的所有数字部分
								const aMatches = (a.name.match(/\d+/g) || []).map(Number);
								const bMatches = (b.name.match(/\d+/g) || []).map(Number);
				        
				                // 比较每个数字部分，按顺序进行排序
				                for (let i = 0; i < Math.min(aMatches.length, bMatches.length); i++) {
				                    if (aMatches[i] !== bMatches[i]) {
				                        return aMatches[i] - bMatches[i];
				                    }
				                }
				        
				                // 如果所有数字部分都相同，则认为两者相等
				                return 0;
				            });
				        
				            // 设置索引
				            group.forEach((dv, index) => {
				                dv.index = index;
				            });
				        
				            return group;
				        });
						this.areaList = areaList
						console.log('this.areaList', this.areaList)
				    }
				}
				setTimeout(() => {
					uni.hideToast()
				}, 500)
			},
			// 获取当前栋舍id下的拍照记录
			async getRecordsList() {
				const params = {
					building_id: this.buildId,
					start_time: `${this.date} 00:00:00`,
					end_time: `${this.date} 23:59:59`,
					page: 1,
					page_size: 50
				}
				const data = await getRecordsById(params)
				const history = data?.records ?? []
				this.history = history.map(item => {
					item.operation_time = dayjs(item.operation_time).format('MM-DD hh:mm')
					return item
				})
				const token = uni.getStorageSync('token')
				const users = uni.getStorageSync('aiUserInfo')
				if (data.records && data.records.length) {
					uni.request({
						url: `${getRecordFeedListAsAi}${users.enterprise_id}&page=1&page_size=50&search_docking_id__in=` + JSON.stringify(data.records.map(item => item.id)),
						method: 'get',
						dataType: 'json',
						header: {
							authorization: token
						},
						success: (res) => {
							this.history = history.map(item => {
								item.ai_has_feed = res.data.data.find(kt => kt.docking_id == item.id)?.ai_has_feed ?? "未知"
								item.operation_time = dayjs(item.operation_time).format('MM-DD hh:mm')
								return item
							})
						},
						fail: () => {
							this.history = history.map(item => {
								item.operation_time = dayjs(item.operation_time).format('MM-DD hh:mm')
								return item
							})
						},
						complete: () => {
							uni.hideLoading()
						}
					})
				}
				console.log(history, this.history)
				const historyIds = this.history.map(item => item.column_id)
				const area = this.build.find(item => item.id == this.buildId)
				this.hasPig = area.farm_scene.filter(item => item.has_pig)
				if (area.farm_scene && area.farm_scene.length) {
					const offlineInfo = uni.getStorageSync(`build-${this.buildId}`)
					if (offlineInfo && offlineInfo.length) {
						this.offlineInfo = offlineInfo
					} else {
						this.offlineInfo = this.hasPig.map((item, $index) => {
							// status 1 空 白色 2 已选择照片 黄色 3 已上传照片 紫色 4 上传失败 红色 
							// 查找历史记录里是否有当前id对应的数据
							const currentArea = this.history.find(dv => dv.column_id === item.id)
							const obj = {
								id: item.id,
								index: item?.index ?? $index,
								poster: currentArea?.image ?? '',
								status: historyIds.includes(item.id) ? 3 : 1,
								info: {
									image: currentArea?.image ?? '',
									shape: currentArea?.shape ?? (area.shape || '圆形'),    
									column_id: item.id,
									column_name: item.name,
									building_id: this.buildId,
									feed_slot_id: 1,
									feed_slot_name:'料槽',
									material_status: currentArea?.material_status ?? '',
									occlusion_level: currentArea?.occlusion_level ?? '',
									operation_executed: currentArea?.operation_executed ?? ''
								}
							}
							if (obj.status == 3) {
								obj.poster = this.file + obj.poster
							}
							return obj
						})
						this.offlineInfo.sort((a, b) => a.id - b.id)
					}					
				}
				this.initMapData();
			},
			base64ToFile(base64, filename) {
				let arr = base64.split(',');
				let mime = arr[0].match(/:(.*?);/)[1];
				let bstr = atob(arr[1]);
				let n = bstr.length;
				let u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new File([u8arr], filename, {
					type: mime
				});
			},
			compressH5(fileItem) {
				return new Promise((resolve, reject) => {
					let file_size = fileItem.size
					let file_path = fileItem.path
					let file_name = fileItem.name
					let max_size = 1020 * 1020 * 1 // 2MB的图片
					if (max_size > file_size) { // 判断是否需要压缩, 没有超过限制
						resolve(fileItem)
					} else {
						let img = new Image();
						img.src = file_path;
						img.onload = function() {
							var quality = max_size / file_size
							var that = this;
							var h = that.height * (quality / 1); // 默认按比例压缩		
							var w = that.width * (quality / 1);
							var canvas = document.createElement('canvas');
							var ctx = canvas.getContext('2d');
							var anw = document.createAttribute("width");
							anw.nodeValue = w;
							var anh = document.createAttribute("height");
							anh.nodeValue = h;
							canvas.setAttributeNode(anw);
							canvas.setAttributeNode(anh);
							ctx.drawImage(that, 0, 0, w, h); //压缩比例		
							// base64
							var base64 = canvas.toDataURL('image/jpeg', quality);
							canvas = null;
							// file对象
							// var file = that.base64ToFile(base64, "file_" + Date.parse(new Date()) + ".jpg");
							// 创建一个Blob对象，表示Base64编码的数据  
							var blob = new Blob([base64], { type: 'application/octet-stream' });  
							// 创建一个新的File对象，使用Blob对象作为其数据  
							var file = new File([blob], Date.parse(new Date()) + ".jpg", { type: 'image/png' });  
							resolve(file)
						}
					}
				})
			},
			fileUpload(file, index) {  
			  return new Promise((resolve, reject) => {  
			    const $that = this;  
			    var formdata = new FormData();  
			    formdata.append("file", file);  
			    var xhr = new XMLHttpRequest();  
			    xhr.onreadystatechange = () => {  
			      if (xhr.readyState === 4) {  
			        if (xhr.status === 200) {  
			          const data = JSON.parse(xhr.responseText);  
			          if (data && data.filename) {  
			            // console.log('进入到解析之后 开始关闭操作');  
			            // uni.hideToast();  
			            // $that.offlineInfo[index].info.image = data.filename;  
			            // $that.offlineInfo[index].poster = data.filename;  
			            // $that.offlineInfo[index].status = 3;  
			            // $that.count++;  
			            // this.logsTipsForm.image = data.filename;  
			            resolve(data); // 解析 Promise  
			          } else {  
			            // $that.offlineInfo[index].status = 4;  
			            reject(); // 解析 Promise  
			          }  
			        } else {  
			          reject(); // 拒绝 Promise  
			        }  
			      }  
			    };  
			    const token = uni.getStorageSync('token');  
			    xhr.open("post", uploads, true); // 请确保 uploads 是正确的上传 URL  
			    xhr.setRequestHeader('Authorization', `bearer ${token}`);  
			    xhr.send(formdata);  
			  });  
			},
			// 保存全部离线文件
			saveOfflineAlls() {
				// uni.showLoading({
				// 	title: `正在上传`,
				// 	mask: true
				// })
				console.log('到这里到这里')
				this.uploads = this.offlineInfo.filter(item => item.status == 2)
				this.setUploadPics()
				// uni.showModal({
				// 	title: '提示',
				// 	content: '到这里了'
				// })
			}, 
			// 计算是否还有为拍摄的栏位
			setOfflineNeedCreame() {
				this.offlineNeedCreame = this.offlineInfo.some(item => item.status == 1)
			},
			// 保存离线
			saveOffline() {
				this.logsTipsStatus = false
				const offline = this.offlineInfo.filter(item => item.poster)
				if (offline && offline.length) {
					this.offlineLens = offline.length
				}
				this.offlineNoPoster = this.offlineInfo.some(item => item.status != 1)
				uni.setStorageSync(`build-${this.buildId}`, this.offlineInfo)
			},
			// 下一个保存离线
			saveOfflineNext() {
				// 查看offlineInfo中poster为空的第一个
				// const offlineNo = this.offlineInfo.filter(item => item.status == 1)
				// const first = offlineNo[0]
				// this.offlineIndex = this.offlineInfo[this.offlineIndex].index++
				// if (this.offlineIndex > this.hasPig.length) {
				// 	this.$u.toast('已经拍完了')
				// 	return false
				// }
				// this.offlineIndex = this.offlineInfo.findIndex(item => item.status == 1)
				this.offlineIndex++
				this.maskColumnsIndex = -1
				this.offlineNoPoster = this.offlineInfo.some(item => item.status == 1)
				if (this.offlineIndex > this.offlineInfo.length) {
					this.$u.toast('已经拍完了')
					return false
				}
				const offline = this.offlineInfo.filter(item => item.poster)
				this.offlineLens = offline.length
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (temp) => {
						this.offlineInfo.forEach((item, $index) => {
							if (this.offlineIndex == $index) {
								item.status = 2
								item.poster = temp.tempFilePaths[0]
								// item.file = temp.tempFiles[0]
								this.compressH5(temp.tempFiles[0]).then(res => {
									item.file = res
								})
								this.areaList = this.areaList.map(dv => {
									if (dv && dv.length) {
										const currentDv = dv.find(dt => dt.id == item.id)
										if (currentDv) {
											currentDv.status = item.status
										}
									}
									return dv
								})
							}
						})
						this.logsTipsStatus = true;
						const needStorage = this.offlineInfo.some(item => item.status == 2)
						if (needStorage) {
							uni.setStorageSync(`build-${this.buildId}`, this.offlineInfo)
						} else {
							uni.removeStorageSync(`build-${this.buildId}`)
						}
					},
					fail: (err) => {
						console.log('err', err)
					}
				})
			},
			// 删除某一个栏位的信息
			delLogsTips(index) {
				console.log(index);
				const currentColumn = {
					...this.offlineInfo[index]
				}
				currentColumn.poster = ''
				currentColumn.file = null
				currentColumn.status = 1
				this.offlineInfo.splice(index, 1, currentColumn)
				this.areaList = this.areaList.map(dv => {
					if (dv && dv.length) {
						const currentDv = dv.find(dt => dt.id == currentColumn.id)
						if (currentDv) {
							currentDv.status = 1
						}
					}
					return dv
				})
			},
			// 点击栏位进行拍照
			setLogsTips(id, name, type, status) {
				this.logsTipsForm.column_id = id
				this.logsTipsForm.column_name = name
				if (!type) {
					this.$u.toast(name + '空栏不需要拍照')
					return false
				}
				if (status == 1) {
					uni.chooseImage({
						count: 1,
						sizeType: ['compressed'],
						sourceType: ['camera', 'album'],
						success: (temp) => {
							this.offlineInfo.forEach((item, $index) => {
								if (id == item.id) {
									this.offlineIndex = $index
									item.status = 2
									item.poster = temp.tempFilePaths[0]
									// item.file = temp.tempFiles[0]
									this.compressH5(temp.tempFiles[0]).then(res => {
										item.file = res
									})
									this.areaList = this.areaList.map(dv => {
										if (dv && dv.length) {
											const currentDv = dv.find(dt => dt.id == item.id)
											if (currentDv) {
												currentDv.status = item.status
											}
										}
										return dv
									})
								}
							})
							// this.tempFile = temp.tempFiles
							// this.tempFilePaths = temp.tempFilePaths
							// this.setUploadPics();
							this.logsTipsStatus = true;
						},
						fail: (err) => {
							console.log('err', err)
						}
					})
				} else {
					this.offlineIndex = this.offlineInfo.findIndex(item => item.id == id)
					this.logsTipsStatus = true
				}
			},
			// 点击下一步继续拍照
			getNextColumn() {
				// this.chooseImage()
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (temp) => {
						this.offlineTemp = temp.tempFilePaths[0]
						// this.tempFile = temp.tempFiles
						// this.tempFilePaths = temp.tempFilePaths
						// this.setUploadPics();
					},
					fail: (err) => {
						console.log('err', err)
					}
				})
			},
			// 保存
			save(flag) {
				uni.showToast({
					title: '正在识别...',
					icon: 'loading',
					mask: true,
					duration: 10000
				})
				const params = {
					...this.logsTipsForm,
					building_id: this.buildId,
					feed_slot_id: 1,
					feed_slot_name:'料槽',
					shape: this.buildShape
				}
				setRecords(params).then(res => {
					this.getRecordsList()
					setTimeout(() => {
						if (!flag) {
							this.picsTipsStatus = false
							this.logsTipsStatus = false
						} else {
							this.areaHasPigs = this.areaList.flat().filter(item => !item.poster && item.has_pig)
							if (this.areaHasPigs && this.areaHasPigs.length) {
								this.logsTipsForm = {							
									image: '',
									shape: '',
									column_id: this.areaHasPigs[0].id,
									column_name: this.areaHasPigs[0].name,
									material_status: '适量',
									occlusion_level: '50%以下',
									operation_executed: '没有操作'
								}
								this.logsKey++
							} else {
								this.$u.toast('已拍完')
							}
						}
					}, 300)
				}).catch(err => {
					this.$u.toast('上传失败')
				})
				if (flag) {
					// this.getNextColumn()
					uni.chooseImage({
						count: 1,
						sourceType: ['camera'],
						success: (temp) => {
							this.tempFile = temp.tempFiles
							this.tempFilePaths = temp.tempFilePaths
							this.setUploadPics();
						},
						fail: (err) => {
							console.log('err', err)
						}
					})
				}
			},
			setPicsTipsStatus() {
				console.log(this.areaList)
				if (this.areaList.every(item => item.has_pig === false)) {
					this.$u.toast('空栏不需要拍照')
					return false
				}
				this.picsTipsStatus = !this.picsTipsStatus
			},
			setLogsTipsStatus() {
				this.logsTipsStatus = !this.logsTipsStatus
			},
			// 获取栏位id和栏位name
			setAreaInfo(e) {
				if (!e.value[0].has_pig) {
					this.$u.toast(e.value[0].name + '空栏不需要拍照')
					return false
				}
				// 将当前信息跟选中的栏位交换 如果选中的栏位已拍则提示
				const checkedIndex = this.offlineInfo.findIndex(item => item.id == e.value[0].id)
				this.offlineInfo[checkedIndex].poster = this.offlineInfo[this.offlineIndex].poster
				this.offlineInfo[checkedIndex].file = this.offlineInfo[this.offlineIndex].file
				this.offlineInfo[checkedIndex].status = this.offlineInfo[this.offlineIndex].status
				this.offlineInfo[checkedIndex].info.image = this.offlineInfo[this.offlineIndex].info.image
				this.offlineInfo[checkedIndex].info.material_status = this.offlineInfo[this.offlineIndex].info.material_status
				this.offlineInfo[checkedIndex].info.occlusion_level = this.offlineInfo[this.offlineIndex].info.occlusion_level
				this.offlineInfo[checkedIndex].info.operation_executed = this.offlineInfo[this.offlineIndex].info.operation_executed
				this.offlineInfo[this.offlineIndex].info.poster = ''
				this.offlineInfo[this.offlineIndex].info.file = ''
				this.offlineInfo[this.offlineIndex].info.status = 1
				this.offlineInfo[this.offlineIndex].info = {
					...this.offlineInfo[this.offlineIndex].info,
					image: '',
					material_status: '适量',
					occlusion_level: '',
					operation_executed: '无'
				}
				const info = this.offlineInfo[checkedIndex]
				this.areaList = this.areaList.map(dv => {
					if (dv && dv.length) {
						const currentDv = dv.find(dt => dt.id == info.id)
						if (currentDv) {
							currentDv.status = info.status
						}
						const oldDv = dv.find(dt => dt.id == this.offlineInfo[this.offlineIndex].id)
						if (oldDv) {
							oldDv.status = 1
						}
					}
					return dv
				})
				this.offlineIndex = checkedIndex
				this.areaStatus = false
			},
			// 获取actionsheet的数据
			setColumns(e, key) {
				// this.logsTipsForm[key] = e.name
				this.offlineInfo[this.offlineIndex].info[key] = e.name
			},
			// 选择图片
			chooseImage () {
				// 直接打开下一个弹窗
				// this.setLogsTipsStatus();
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (temp) => {
						const offlineNo = this.offlineInfo.filter(item => item.status == 1)
						const first = offlineNo[0]
						this.offlineIndex = this.offlineInfo.findIndex(item => item.id == first.id)
						this.offlineTemp = temp.tempFilePaths[0]
						const info = this.offlineInfo[this.offlineIndex]
						info.poster = this.offlineTemp
						info.status = 2
						// info.file = temp.tempFiles[0]
						this.compressH5(temp.tempFiles[0]).then(res => {
							info.file = res
						})
						this.offlineInfo.splice(this.offlineIndex, 1, info)
						this.areaList = this.areaList.map(dv => {
							if (dv && dv.length) {
								const currentDv = dv.find(dt => dt.id == info.id)
								if (currentDv) {
									currentDv.status = info.status
								}
							}
							return dv
						})
						// this.offlineInfo[this.offlineIndex].poster = this.offlineTemp
						// this.offlineInfo[this.offlineIndex].status = 2
						// this.offlineKey++
						this.picsTipsStatus = false
						this.logsTipsStatus = true
					},
					fail: (err) => {
						console.log('err', err)
						this.$u.toast('测试失败了')
					}
				})
			},
			// 上传图片
			setUploadPics () {
				const token = uni.getStorageSync('token')
				uni.showToast({
					title: `上传(${this.count + 1}/${this.uploads.length})`,
					icon: 'loading',
					mask: true,
					duration: 10000
				})
				console.log('继续往下执行')
				// #ifdef H5
				if (this.count < this.uploads.length) {
					if (!this.uploads[this.count].poster.includes('blob')) {
						this.fileUpload(this.uploads[this.count].file).then(res => {
							const data = { ...res }
							if (data.filename) {
								const index = this.uploads[this.count].index
								this.uploads[this.count].info.image = data.filename
								this.uploads[this.count].poster = data.filename
								this.uploads[this.count].status = 3
								setRecords(this.uploads[this.count].info).then(res => {									
									this.count++
									this.setUploadPics()
								})
							} else {
								const index = this.uploads[this.count].index
								this.offlineInfo[index].status = 4
								this.count++
								this.setUploadPics()
							}
							uni.setStorageSync(`build-${this.buildId}`, this.offlineInfo)
						})
					} else {
						console.log('this.uploads[this.count]', this.uploads[this.count])
						uni.uploadFile({
							url: `${uploads}`,
							filePath: this.uploads[this.count].poster,
							data: {
								filename: this.uploads[this.count].poster
							},
							headers: {
								Authorization: `bearer ${token}`
							},
							success: (res) => {
								const data = JSON.parse(res.data)
								if (data) {
									this.uploads[this.count].info.image = data.filename
									this.uploads[this.count].poster = data.filename
									this.uploads[this.count].status = 3
									setRecords(this.uploads[this.count].info).then(res => {							
										setTimeout(() => {
											this.count++
											this.setUploadPics()
										}, 1100)
									})
								} else {
									const index = this.uploads[this.count].index
									this.offlineInfo[index].status = 4		
									setTimeout(() => {
										this.count++
										this.setUploadPics()
									}, 1100)
								}
								uni.setStorageSync(`build-${this.buildId}`, this.offlineInfo)
							},						
							fail: (err) => {
								const index = this.uploads[this.count].index
								this.offlineInfo[index].status = 4
							}
						})
					}
				} else {
					uni.hideLoading()
					this.$u.toast('上传完成')
					this.getRecordsList()
					this.count = 0
					this.uploads = []
				}
				// #endif
				// #ifndef H5
				console.log('需要上传的文件', this.uploads)
				// uni.showModal({
				// 	title: '提示',
				// 	content: '需要上传的文件'
				// })
				if (this.count < this.uploads.length) {
					const filename = `${this.uploads[this.count].info.column_name}/${this.uploads[this.count].info.building_id}/${this.defaultDate}`
					uploadFile(this.uploads[this.count].poster, 'example').then(res => {
						console.log('res', res)
						this.uploads[this.count].info.image = `http://lcimg.xee.link/${res}`
						this.uploads[this.count].poster = `http://lcimg.xee.link/${res}`
						this.uploads[this.count].status = 3
						this.uploads[this.count].info.material_status = '适量'
						setRecords(this.uploads[this.count].info).then(res => {
							setTimeout(() => {
								this.count++
								this.setUploadPics()
								uni.setStorageSync(`build-${this.buildId}`, this.offlineInfo)
							}, 200)
						}).catch(err => {
							console.log('保存失败', err)
							const index = this.uploads[this.count].index
							this.offlineInfo[index].status = 4
							setTimeout(() => {
								this.count++
								this.setUploadPics()
								uni.setStorageSync(`build-${this.buildId}`, this.offlineInfo)
							}, 200)
						})
					}).catch(err => {
						console.log('err', err)
					})
					// uni.uploadFile({
					// 	url: `${uploads}`,
					// 	filePath: this.uploads[this.count].poster,
					// 	name: 'file',
					// 	data: {
					// 		filename
					// 	},
					// 	headers: {
					// 		Authorization: `bearer ${token}`
					// 	},
					// 	success: (res) => {
					// 		console.log('res-上传成功',  res)
					// 		// uni.showModal({
					// 		// 	title: '提示',
					// 		// 	content: '上传成功了'
					// 		// })
					// 		const data = JSON.parse(res.data)
					// 		if (data && data.filename) {
					// 			this.uploads[this.count].info.image = data.filename
					// 			this.uploads[this.count].poster = data.filename
					// 			this.uploads[this.count].status = 3
					// 			this.uploads[this.count].info.material_status = '适量'
					// 			setRecords(this.uploads[this.count].info).then(res => {
					// 				setTimeout(() => {
					// 					this.count++
					// 					this.setUploadPics()
					// 				}, 1100)
					// 			}).catch(err => {
					// 				console.log('保存失败', err)
					// 			})
					// 		} else {
					// 			const index = this.uploads[this.count].index
					// 			this.offlineInfo[index].status = 4
					// 			setTimeout(() => {
					// 				this.count++
					// 				this.setUploadPics() 
					// 			}, 1100)
					// 		}
					// 		uni.setStorageSync(`build-${this.buildId}`, this.offlineInfo)
					// 	},						
					// 	fail: (err) => {
					// 		const index = this.uploads[this.count].index
					// 		this.offlineInfo[index].status = 4
					// 		uni.setStorageSync(`build-${this.buildId}`, this.offlineInfo)
					// 	}
					// })
				} else {
					uni.hideLoading()
					this.$u.toast('上传完成')
					this.getRecordsList()
					this.count = 0
					this.uploads = []
					console.log('上传完成了')
				}
				// #endif
			},
			// 以下是给H5用的
			setLogsTipsH5(id, name) {
				this.logsTipsForm.column_id = id
				this.logsTipsForm.column_name = name
				this.logsTipsForm.shape = this.buildShape
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (temp) => {
						this.$u.toast('测试成功了')
						this.tempFile = temp.tempFiles
						this.tempFilePaths = temp.tempFilePaths
						this.setUploadPicsH5();
					},
					fail: (err) => {
						console.log('err', err)
						this.$u.toast('测试失败了')
					}
				})
			},
			// 选择图片
			chooseImageH5 () {
				// 直接打开下一个弹窗
				// this.setLogsTipsStatus();				
				const offlineNo = this.offlineInfo.filter(item => item.status == 1)
				const first = offlineNo[0]
				this.logsTipsForm.column_id = first.info.column_id
				this.logsTipsForm.column_name = first.info.column_name
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (temp) => {
						this.$u.toast('测试成功了')
						this.tempFile = temp.tempFiles
						this.tempFilePaths = temp.tempFilePaths
						this.setUploadPicsH5();
					},
					fail: (err) => {
						console.log('err', err)
						this.$u.toast('测试失败了')
					}
				})
			},
			// 上传图片
			setUploadPicsH5 () {
				if (this.tempFile.length === 0) {
					this.$u.toast('请先选择图片')
					return false
				}
				const token = uni.getStorageSync('token')
				uni.showToast({
					title: '正在上传...',
					icon: 'loading',
					mask: true,
					duration: 10000
				})
				// uploadFile(this.tempFilePaths[0]).then(res => {
				// 	console.log('res', res)
				// }).catch(err => {
				// 	console.log('err', err)
				// })
				uploadFile(this.tempFilePaths[0], 'example').then(res => {
					console.log('res', res)
					// this.uploads[this.count].info.image = `http://lcimg.xee.link/${res}`
					// this.uploads[this.count].poster = `http://lcimg.xee.link/${res}`
					// this.uploads[this.count].status = 3
					// this.uploads[this.count].info.material_status = '适量'
					// feed_slot_id: 1,
					// feed_slot_name:'料槽',
					// const index = this.uploads[this.count].index
					this.logsTipsForm.feed_slot_id = 1
					this.logsTipsForm.feed_slot_name = '料槽'
					// this.logsTipsForm.status = 3
					// this.logsTipsForm.poster = `http://lcimg.xee.link/${res}`
					// this.logsTipsForm.info.image = `http://lcimg.xee.link/${r1es}`
					this.logsTipsForm.building_id = this.buildId
					this.logsTipsForm.image = `http://lcimg.xee.link/${res}`;
					setRecords(this.logsTipsForm).then(res => {
						setTimeout(() => {
							// this.setUploadPics()
							this.getRecordsList()
							uni.setStorageSync(`build-${this.buildId}`, this.offlineInfo)
						}, 200)
					}).catch(err => {
						console.log('保存失败', err)
						// const index = this.uploads[this.count].index
						// this.offlineInfo[index].status = 4
						setTimeout(() => {
							this.count++
							// this.setUploadPics()
							uni.setStorageSync(`build-${this.buildId}`, this.offlineInfo)
						}, 200)
					})
				}).catch(err => {
					console.log('err', err)
				})
				// uni.uploadFile({
				// 	url: 'https://feedslot.oss-cn-beijing.aliyuncs.com',
				// 	filePath: this.tempFilePaths[0],
				// 	name: 'file',
				// 	formData: {
				// 		key: dir + '/' + Date.now() + '.jpg', // 设置上传到OSS的文件名
				// 		policy: policy,
				// 		OSSAccessKeyId: accessKeyId,
				// 		signature: signature,
				// 		success_action_status: '200'
				// 	},
				// 	success: (uploadRes) => {
				// 		console.log('上传成功', uploadRes);
				// 		// 处理上传成功的逻辑
				// 	},
				// 	fail: (err) => {
				// 		console.log('上传失败', err);
				// 		// 处理上传失败的逻辑
				// 	}
				// });
				// for (let i = 0; i < this.tempFile.length; i++) {
				// 	console.log('ces 装备上传', this.tempFilePaths[i])
				// 	uni.uploadFile({
				// 		url: uploads,
				// 		filePath: this.tempFilePaths[i],
				// 		name: 'file',
				// 		data: {
				// 			filename: 'test',
				// 		},
				// 		header: {
				// 			Authorization: `bearer ${token}`
				// 		},
				// 		success: (res) => {
				// 			uploadImgCount++
				// 			console.log('看看返回值', res)
				// 			const data = JSON.parse(res.data)
				// 			if (data) {
				// 				uni.hideToast()
				// 				this.logsTipsForm.image = data.filename;
				// 				this.logsTipsStatus = true;
				// 				console.log('设置显示', this.logsTipsForm, this.logsTipsStatus)
				// 				this.picsTipsStatus = false;
				// 			}
				// 		},
				// 		fail: (err) => {
				// 			uni.showModal({
				// 				title: '错误提示',
				// 				content: '上传图片失败',
				// 				showCancel: false
				// 			})
				// 		}
				// 	})
				// }
			},
		},
		onBackPress() {},
		onPullDownRefresh () {},
		onShareAppMessage () {}
	}
</script>

<style lang="less">
	page {
		background: #fff;
	}
</style>

<style lang="less" scoped>
	.sp-oa__boxes-legend {
		display: flex;
		align-items: center;
		gap: 20rpx;
		font-size: 24rpx;
		
		text {
			display: flex;
			align-items: center;
			
			&:before {
				content: '';
				display: block;
				width: 16rpx;
				height: 16rpx;
				margin-right: 10rpx;
				border: 2px solid;
			}
			
			&:nth-child(1):before {
				background: #846BFE;
				border-color: #846BFE;
			}
			
			&:nth-child(2):before {
				background: #fff;
				border-color: #E6A23C;
			}
		}
	}
	.sp-room__logs {
		margin-top: 24rpx;
	}
	.sp-room__submit {
		display: flex;
		gap: 30rpx;

		button {
			flex: 1;
		}
	}
	.sp-room__link {
		display: block;
		padding: 0 20rpx;
		font-size: 24rpx;
		color: #846BFE;
		line-height: 82rpx;
	}
	.sp-room__scroll {
		
		&- {
			
			&list {
				padding-left: 8rpx;
				&:not(:first-child) {
					margin-top: 20rpx;
				}
			}
			
			&item {
				display: inline-block;
				width: 100rpx;
				height: 68rpx;
				line-height: 66rpx;
				margin-right: 24rpx;
				border: 1rpx solid #846BFE;
				box-sizing: border-box;
				font-size: 24rpx;
				text-align: center;
				
				&.active {
					background: #846BFE;
					color: #fff;
				}
				
				&.warning {
					background: #E6A23C;
					color: #fff;
				}
				
				&.danger {
					background: #F56C6C;
					color: #fff;
				}
				
				&.disabled {
					background: #ccc;
					color: #fff;
				}
			}
		}
	}
	.sp-room__form {
		display: flex;
		flex-direction: column;
		height: 100vh;
		overflow: scroll;
		padding-bottom: 140rpx;
		box-sizing: border-box;
		
		&- {
			
			&tags {
				display: flex;
				padding-top: 5px;
				
				text {
					display: block;
					font-size: 24rpx;
					color: #666;
					border: 1rpx solid #ccc;
					border-radius: 2rpx;
					padding: 10rpx 14rpx;
					box-sizing: border-box;
					margin-left: 20rpx;
					transition: all .3s;
					
					&.active {
						color: #fff;
						background: #846BFE;
						border-color: #846BFE;
					}
				}
			}
			
			&pics {
				position: relative;
				flex: 1;
				padding: 30rpx 0 0;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				
				image {
					display: block;
					width: 100%;
					margin: 0 auto;
				}
				
				& > text {
					width: 100rpx;
					padding: 16rpx 0;
					font-size: 26rpx;
					text-align: center;
					color: #fff;
					position: absolute;
					bottom: 0;
					z-index: 11;
					
					&:nth-child(2) {
						right: 100rpx;
						background: #E6A23C;
					}
					
					&:nth-child(3) {
						right: 0;
						background: #F56C6C;
					}
				}
			}
			
			&title {
				width: 100rpx;
				margin: 0 auto 40rpx;
				padding: 30rpx 0 20rpx;
				border-bottom: 4rpx solid #846BFE;
				text-align: center;
			}
			
			&tips {
				display: flex;
				align-items: flex-start;
				flex-wrap: wrap;
				padding: 0 20rpx;
				
				&-item {
					flex: 0 0 20%;
					padding: 2rpx;
					border: 1rpx solid #fff;
					transition: all .3s;
					box-sizing: border-box;
					
					&.active {
						border-color: #846BFE;
					}
					
					text,
					image {
						display: block;
						width: 90%;
					}
					
					text {
						margin: 10rpx 0;
						font-size: 24rpx;
						text-align: center;
					}
					
					image {
						height: 188rpx;
						margin: 0 auto;
					}
				}
			}
		}
	}
</style>
